#include "CameraController.h"
#include "Graphics.h"
#include "Camera.h"
#include "Input.h"
#include "Time.h"
#include "Camera.h"

using namespace DYGraphics;

CameraController::CameraController(): InputEventHandle()
{
	mCamera = nullptr;
	mIsPressLeft = false;
	mIsPressRight = false;
	mStartX = 0;
	mStartY = 0;
	mCamT = nullptr;
}

CameraController::CameraController(Camera* pCamera) : InputEventHandle()
{
	mCamera = pCamera;
	mIsPressLeft = false;
	mIsPressRight = false;
	mStartX = 0;
	mStartY = 0;
	mCamT = mCamera->GetTransform();
}

CameraController::~CameraController()
{

}

void CameraController::BindCamera(Camera* pCamera)
{
	mCamera = pCamera;
	mCamT = mCamera->GetTransform();
}

void CameraController::MouseButtonPress(int key, int action)
{
	if (key == (int)MouseButton::LEFT)
	{
		if (action == (int)KeyPressMode::Down)
		{
			mIsPressLeft = true;
			Input::GetCursorPos(mStartX, mStartY);
		}
		else if (action == (int)KeyPressMode::Up)
		{
			mIsPressLeft = false;
		}
	}
	else if(key == (int)MouseButton::RIGHT)
	{
		if (action == (int)KeyPressMode::Down)
		{
			mIsPressRight = true;
			Input::GetCursorPos(mStartX, mStartY);
		}
		else if (action == (int)KeyPressMode::Up)
		{
			mIsPressRight = false;
		}

	}
}

void CameraController::CursorMove(float cursorX, float cursorY)
{
	if (mIsPressLeft)
	{
		float deltaX = cursorX - mStartX;
		float deltaY = cursorY - mStartY;

		const float speed = 0.1f;
		float deltaTime = Time::GetDeltaTime();
		glm::vec3 pos = mCamT->GetPosition();
		pos.x -= speed * deltaX * deltaTime;
		pos.y += speed * deltaY * deltaTime;
		mCamT->SetPosition(pos);

		mStartX = cursorX;
		mStartY = cursorY;
	}
	else if (mIsPressRight)
	{
		float deltaX = cursorX - mStartX;
		float deltaY = cursorY - mStartY;

		const float speed = 0.01f;
		float deltaTime = Time::GetDeltaTime();
		glm::vec3 rot = mCamT->GetRotation();
		rot.y -= speed * deltaX * deltaTime;
		rot.x -= speed * deltaY * deltaTime;
		mCamT->SetRotation(rot);

		mStartX = cursorX;
		mStartY = cursorY;
	}
}

void CameraController::ScrollEvent(float xoffset, float yoffset)
{
	const float speed = 0.1f;
	float dt = Time::GetDeltaTime();
	float dist = yoffset * speed;
	glm::vec3 pos = mCamT->GetPosition();
	pos.z += dist;
	mCamT->SetPosition(pos);
}

void CameraController::ScreenSizeChange(float x, float y)
{

}

void CameraController::KeyPress(int key, int action)
{

}